if ( cash >= price )
You (hopefully) picked a relational operator that yields true when the user CAN pay for the sweater.
Here is what happens for one run of the program:
How much do you have, in pennies? 5000 You can buy the sweater
The true block was executed because the boolean expression was true. Here is another run of the program:
How much do you have, in pennies? 2000 You can't buy the sweater You need $24.95 more.
The false block executed because the boolean expression was false.
Remember that boolean expressions are always
true or false.
By using the correct relational operator (==, >, <,
etc.)
you ask a question that is true when you
want the true branch to be executed.
The true branch is not necessarily the "good choice."
If the statements inside of the two branches are switched
you will have to change the
relational operator for the
program to do the same thing as before.
Here is the program again, with the statements of the true and false branches switched.
import java.io.*; class SweaterPurchase { public static void main (String[] args) throws IOException { final int price = 4495; // price in cents BufferedReader stdin = new BufferedReader ( new InputStreamReader( System.in ) ); String inData; int cash; System.out.println("How much do you have, in pennies?"); inData = stdin.readLine(); cash = Integer.parseInt( inData ); if ( __________________ ) { System.out.println("You can't buy the sweater" ); System.out.println("You need $" + (price-cash)/100 + "." + (price-cash)%100 + " more." ); } else System.out.println("You can buy the sweater" ); } }